package com.tzy.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tzy.springboot.entity.SystemLog;
import com.tzy.springboot.mapper.SystemLogMapper;
import com.tzy.springboot.service.ISystemLogService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class SystemLogServiceImpl extends ServiceImpl<SystemLogMapper, SystemLog>
        implements ISystemLogService {

    @Override
    public void saveLog(String level, String module, String content, String userName) {
        SystemLog log = new SystemLog();
        log.setLevel(level);
        log.setModule(module);
        log.setContent(content);
        log.setUserName(userName);
        log.setCreateTime(LocalDateTime.now());
        log.setIp(getClientIp());
        this.save(log);
    }

    @Override
    public void saveLog(SystemLog log) {
        if (log.getCreateTime() == null) {
            log.setCreateTime(LocalDateTime.now());
        }
        if (log.getIp() == null) {
            log.setIp(getClientIp());
        }
        this.save(log);
    }

    private String getClientIp() {
        try {
            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String ip = request.getHeader("X-Forwarded-For");
                if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("X-Real-IP");
                }
                if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
                return ip;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0:0:0:0:0:0:0:1";
    }
}
